﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ECMS.Infrastructure.Engines;
using ECMS.Manage.Authorizations;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using StructureMap;

namespace ECMS.Manage
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(opt => opt.EventsType = typeof(ECMSCookieAuthenticationEvents));
            services.AddScoped<ECMSCookieAuthenticationEvents>();

            var connectionString = Configuration.GetConnectionString("ECMSConnection");
            // 配置数据库上下文
            services.AddDbContext<Domain.ECMSDbContext>(opt => opt.UseSqlServer(connectionString, p => p.MigrationsAssembly("ECMS.Domain")));

            services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();

            // 注入服务
            BootStrapper.ECMSIocConfiguration.AddIocConfiguration(services);

            var container = new Container();
            container.Populate(services);
            EngineContainerFactory.InitializeEngineContainerFactory(new EngineContainer(container));

            return container.GetInstance<IServiceProvider>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseAuthentication();
            app.UseCookiePolicy();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}
